from django_redis import get_redis_connection
from redis import RedisError
from rest_framework import serializers

import logging
logger = logging.getLogger('django')


class InageCodeCheckSerializers(serializers.Serializer):

    '''图片验证码校验序列化器'''
    image_code_id = serializers.UUIDField()
    text = serializers.CharField(max_length=4,min_length=4)

    def validate(self,attr):

        '''校验'''
        image_code_id = attr['image_code_id']
        text = attr['text']

         #查询真实图片验证码
        redis_coon = get_redis_connection('verify_codes')
        image_code_server = redis_coon.get('image_%s'%image_code_id)
        if image_code_server is None:
            return serializers.ValidationError('图片验证码无效')

        #删除图片
        try:
            redis_coon.delete('image_%s' % image_code_id)
        except RedisError as e:
            #自己捕获异常不能影响主线逻辑
            logger.error(e)

        #redis读取的数据为二进制需要解码
        image_code_server = image_code_server.decode()

        # 比较图片验证码
        if text.lower() != image_code_server.lower():
            return serializers.ValidationError('图片验证码错误')

        #判断是否在60秒之内
        mobile = self.context['view'].kwargs['mobile']
        send_flag = redis_coon.get('send_flag_%s' %mobile)
        if send_flag:
            return serializers.ValidationError('请求频繁')

        return attr


































